// 1. 从 react-router-dom 引入 useNavigate 这个 Hook
// import { useNavigate } from "react-router-dom";

const http = (url: any, method: any, data?: any) => {
  // const navigate = useNavigate();
  let token = localStorage.getItem("token");
  data.token = token;
  return new Promise((res, rej) => {
    if (method == "get" || method == "GET") {
      fetch("http://127.0.0.1:9000" + url, {
        headers: {
          "Content-Type": "application/json",
          token: token,
        },
      })
        .then((response) => res(response.json()))
        .then((data) => {
          // console.log("Success:", data);
        })
        .catch((error) => {
          rej(error);
          console.error("Error:", error);
        });
    } else {
      fetch("http://127.0.0.1:9000" + url, {
        method: method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => {
          // 重定向
          let responseJson = response.json();
          responseJson.then((Res) => {
            if (Res.code == 301) {
              console.log("跳转");
              // navigate("/login");
              window.location.pathname = "http://localhost:5173/login";
              return;
            }
          });
          res(responseJson);
        })
        .then((data) => {
          // console.log("Success:", data);
        })
        .catch((error) => {
          rej(error);
          console.error("Error:", error);
        });
    }
  });
};

export default http;
